package controller

import (
	"html/template"
	"log"
	"net/http"
	"strconv"
	"web01/dao"
	"web01/model"

	"github.com/gin-gonic/gin"
	"github.com/russross/blackfriday/v2"
)

func Index(c *gin.Context) {
	c.HTML(http.StatusOK, "index.html", nil)
}

func ListUsers(c *gin.Context) {
	c.HTML(http.StatusOK, "users.html", nil)
}

func GoRegister(c *gin.Context) {
	c.HTML(http.StatusOK, "register.html", nil)
}

func RegisterUser(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")

	user := model.User{
		Username: username,
		Password: password,
	}

	dao.Mgr.Register(&user)

	c.Redirect(http.StatusMovedPermanently, "/")
}

func GoLogin(c *gin.Context) {
	c.HTML(http.StatusOK, "login.html", nil)
}

func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	u := dao.Mgr.Login(username)

	if u.Username == "" {
		c.HTML(http.StatusOK, "login.html", "用户名不存在")
		log.Printf("用户[%v]不存在\n", username)
		return
	}
	if u.Password != password {
		c.HTML(http.StatusOK, "login.html", "用户名或密码错误")
		log.Printf("用户[%v]登录密码错误\n", username)
		return
	}

	log.Printf("用户[%v]登录成功\n", username)
	c.Redirect(http.StatusMovedPermanently, "/")
}

func GetPostIndex(c *gin.Context) {
	posts := dao.Mgr.GetAllPost()
	c.HTML(http.StatusOK, "postIndex.html", posts)
}

func AddPost(c *gin.Context) {
	title := c.PostForm("title")
	content := c.PostForm("content")
	tag := c.PostForm("tag")

	post := model.Post{
		Title:   title,
		Content: content,
		Tag:     tag,
	}

	dao.Mgr.AddPost(&post)

	c.Redirect(http.StatusFound, "/post_index")
}

func GoAddPost(c *gin.Context) {
	c.HTML(http.StatusOK, "post.html", nil)
}

// 展示指定博客文章
func PostDetail(c *gin.Context) {
	s := c.Query("pid")
	pid, _ := strconv.Atoi(s)
	p := dao.Mgr.GetPost(pid + 1)

	// markdown 格式文章转换为 html
	content := blackfriday.Run([]byte(p.Content))

	c.HTML(http.StatusOK, "postDetail.html", gin.H{
		"Title":   p.Title,
		"Content": template.HTML(content),
	})
}
